<?php namespace system\model;

use hdphp\model\Model;

class Category extends Model{

	//数据表
	protected $table = "category";
	//自动验证
	protected $validate=[
		//['字段名','验证方法','提示信息',验证条件,验证时间]
		['cname','required','分类名称不能为空',self::MUST_VALIDATE,self::MODEL_BOTH],
		['ctitle','required','分类标题不能为空',self::MUST_VALIDATE,self::MODEL_BOTH],
		['cdes','required','分类描述不能为空',self::MUST_VALIDATE,self::MODEL_BOTH],
		['ckeywords','required','分类关键字不能为空',self::MUST_VALIDATE,self::MODEL_BOTH],
		['csort','num:1,99999','分类排序必须为数字',self::MUST_VALIDATE,self::MODEL_BOTH],
	];
	/**
	 * 添加分类
	 */
	public function store(){
		if(!$this->create()) return false;
		return $this->add();
	}

	/**
	 * 处理所属分类
	 */
	public function getCateData($cid){
		//先找出所有子集
		$cid = $this->getSon($this->get(),$cid);
		//追加自己进去
		$cids[]=$cid;
		$data = $this->whereNotIn('cid',$cids)->get();
		return Data::tree($data,"cname");

	}
	/**
	 * 递归找子集
	 */
	public function getSon($data,$cid){
		static $temp=[];
		foreach ($data as $k=>$v){
			if($v['pid']==$cid){
				$temp[]=$v['cid'];
				$this->getSon($data, $v['cid']);
			}
		}
		return $temp;
	}
	public function edit(){
		if(!$this->create()) return false;
		return $this->save();
	}


}